/*
 * AGENT SHERPA
 *  
 * Assignement 2 of the Agent Oriented Software Engineering Course
 * M.Sc. in Advanced Software Engineering (Part-time)
 * University College Dublin www.ucd.ie
 *
 * Copyright (c) 2007 Chris Walsh, Aidan Morrisy and Iain Hull.
 * All rights reserved.
 */

package org.agentsherpa;

import java.util.HashMap;
import java.util.Map;

import org.agentsherpa.model.CellType;
import org.agentsherpa.model.Point;

/**
 * Map Utility functions.
 * 
 * @author iain
 */
public class MapUtil {

	public static String encodeMap(Map<Point, CellType> map) {
		StringBuffer buffer = new StringBuffer();
		for (Map.Entry<Point, CellType> e : map.entrySet()) {
			buffer.append(e.getKey().getX());
			buffer.append(" ");
			buffer.append(e.getKey().getY());
			buffer.append(" ");
			buffer.append(e.getValue());
			buffer.append(";");
		}
		return buffer.toString();
	}

	public static Map<Point, CellType> decodeMap(String data) {
		Map<Point, CellType> map = new HashMap<Point, CellType>();
		String[] points = data.split(";");

		for (String rec : points) {
			String[] fields = rec.split(" ");
			int x = Integer.parseInt(fields[0]);
			int y = Integer.parseInt(fields[1]);
			CellType cell = CellType.valueOf(fields[2]);

			map.put(new Point(x, y), cell);
		}
		return map;
	}

	public static void mergeMaps(Map<Point, CellType> dest,
			Map<Point, CellType> newMap) {
		for (Point p : newMap.keySet()) {
			CellType newCell = newMap.get(p);
			if (newCell == CellType.IED) {
				dest.put(p, CellType.IED);
			} else {
				if (newCell == null || newCell == CellType.ROAD) {
					dest.put(p, CellType.CLEARED);
				}
			}
		}
	}
	
	public static String stripQuotes(String data) {
		final String quote = "\"";
        int start = 0;
        int end = data.length();
        
        if (data.startsWith(quote)) {
        	start++;
        }
        
        if (data.endsWith(quote)) {
        	end--;
        }
        
        return data.substring(start, end);
	}
}
